package com.imdroid.carac;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

import org.acra.ACRA;
import org.acra.ErrorReporter;
import org.acra.ReportField;
import org.acra.annotation.ReportsCrashes;
import org.acra.collector.CrashReportData;
import org.acra.sender.ReportSender;
import org.acra.sender.ReportSenderException;
import org.apache.commons.net.ftp.FTPClient;

import android.annotation.SuppressLint;
import android.app.Application;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.content.res.Resources;
import android.os.Environment;
import android.os.Handler;
import android.os.Looper;
import android.preference.PreferenceManager;
import android.telephony.TelephonyManager;
import android.util.Log;
import android.widget.Toast;

import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.baidu.mapapi.BMapManager;
import com.baidu.mapapi.MKGeneralListener;
import com.baidu.mapapi.map.MKEvent;
import com.baidu.platform.comapi.basestruct.GeoPoint;
import com.imdroid.carac.activities.FloatView;
import com.imdroid.carac.activities.HomeActivity;
import com.imdroid.carac.activities.Record;
import com.imdroid.carac.model.Destination;
import com.imdroid.carac.model.User;
import com.imdroid.carac.net.HttpHelper;
import com.imdroid.carac.net.Weibo;
import com.imdroid.carac.services.SecurityService;
import com.imdroid.carac.speechRecog.SpeechRecog;

/**
 * The application of IMDroid
 * 
 */
@ReportsCrashes(formKey = "dGVacG0ydVHnaNHjRjVTUTEtb3FPWGc6MQ")
public class IMDroid extends Application {
	/**
	 * The TAG of the application
	 */
	private static String TAG = "IMDroid";
	/**
	 * the temp folder name.
	 */
	public static String TEMP_FOLDER = Environment
			.getExternalStorageDirectory().getPath() + "/IMDroid/temp/";

	/**
	 * the temp folder name.
	 */
	public static String REC_PIC_FOLDER = Environment
			.getExternalStorageDirectory().getPath() + "/IMDroid/videoPic/";

	/**
	 * the speech recog folder name.
	 */
	public static String SPEECH_RECOG_FOLDER = Environment
			.getExternalStorageDirectory().getPath() + "/IMDroid/speechRecog/";
	/**
	 * Temp folder
	 */
	public static final String TEMP_ERROR = Environment
			.getExternalStorageDirectory() + "/IMDroid/error/";

	/**
	 * the video folder name. 在下面初始化的时候，优先用 VIDEO_FOLDER_1，不行再 VIDEO_FOLDER_2
	 */
	public static String VIDEO_FOLDER;
	private static String VIDEO_FOLDER_1 = "/mnt/sdcard2/IMDroid/video/";

	// private static String VIDEO_FOLDER_1 = Environment
	// .getExternalStorageDirectory().getPath() + "/IMDroid/video/";

	private static String VIDEO_FOLDER_2 = Environment
			.getExternalStorageDirectory().getPath() + "/IMDroid/video/";

	// 暂没有找到好办法得到sdcard2目录
	// private static String VIDEO_FOLDER_2 = Environment
	// .getExternalStorageDirectory().getPath() + "/IMDroid/video/";

	// weibo folder, saving user's weibo token in file "weiboToken"
	public static String WEIBO_FOLDER = Environment
			.getExternalStorageDirectory().getPath() + "/IMDroid/weibo/";

	/**
	 * The cache folder for saving bitmap files.
	 */
	public static String VIDEO_SCREEN_CACHE = Environment
			.getExternalStorageDirectory().getPath() + "/IMDroid/vcache/";

	/**
	 * the file of security file.
	 */
	public static String SECURITY_FOLDER = Environment
			.getExternalStorageDirectory().getPath() + "/IMDroid/security/";

	/**
	 * the file of security file.
	 */
	public static String APP_FOLDER = Environment.getExternalStorageDirectory()
			.getPath() + "/IMDroid/newapp/";
	/**
	 * 目录下最多的文件个数.
	 */
	private static String KEY_REC_FILE_COUNT = "REC_FILE_COUNT";
	/**
	 * 每个文件的文件最大时间.
	 */
	private static String KEY_REC_FILE_LEN = "REC_FILE_LEN";

	/**
	 * The instance of application
	 */
	private static IMDroid instance;
	/**
	 * The current user object
	 */
	private static User currentUser;
	/**
	 * The current location
	 */
	private static BDLocation currentLocation;
	/**
	 * The location client
	 */
	public LocationClient locationClient = null;
	/**
	 * The location listener
	 */
	public BDLocationListener myListener = new MyLocationListener();
	/**
	 * The current location
	 */
	private static boolean batteryCharge = false;
	/**
	 * the baidu map manager
	 */
	public BMapManager mBMapMan = null;
	// The gps location change interval
	public static int ONE_MINUTE = 60;
	public static int THREE_SECOND = 3;

	static {
		// 建立临时文件夹
		File file = new File(TEMP_FOLDER);
		if (!file.exists())
			file.mkdirs();
		// 建立临时文件夹
		file = new File(TEMP_ERROR);
		if (!file.exists())
			file.mkdirs();	
		//建立照片文件夹
		file = new File(REC_PIC_FOLDER);
		if (!file.exists())
			file.mkdirs();
		//建立视屏文件夹
		VIDEO_FOLDER = VIDEO_FOLDER_1;
		file = new File(VIDEO_FOLDER);
		if (!file.exists())
			file.mkdirs();
		if (!file.exists()) { // 不成功说明 VIDEO_FOLDER_2 目录无效，比如没有装 sdcard2
			VIDEO_FOLDER = VIDEO_FOLDER_2;
			file = new File(VIDEO_FOLDER);
			if (!file.exists())
				file.mkdirs();
		}
		//建立微博文件夹
		file = new File(WEIBO_FOLDER);
		if (!file.exists())
			file.mkdirs();
		//建立语音识别文件夹
		file = new File(SPEECH_RECOG_FOLDER);

		//建立理想cache文件夹
		if (!file.exists())
			file.mkdirs();
		file = new File(VIDEO_SCREEN_CACHE);
		//建立安防图片文件夹
		if (!file.exists())
			file.mkdirs();
		file = new File(SECURITY_FOLDER);
		if (!file.exists())
			file.mkdirs();
		file = new File(APP_FOLDER);
		if (!file.exists())
			file.mkdirs();
	}

	// 常用事件监听，用来处理通常的网络错误，授权验证错误等
	static class MyGeneralListener implements MKGeneralListener {

		@Override
		public void onGetNetworkState(int iError) {
			if (iError == MKEvent.ERROR_NETWORK_CONNECT) {
				Toast.makeText(getContext(), "您的网络出错啦！", Toast.LENGTH_LONG)
						.show();
			} else if (iError == MKEvent.ERROR_NETWORK_DATA) {
				Toast.makeText(getContext(), "输入正确的检索条件！", Toast.LENGTH_LONG)
						.show();
			}
		}

		@Override
		public void onGetPermissionState(int iError) {
			if (iError == MKEvent.ERROR_PERMISSION_DENIED) {
				// 授权Key错误：
				Toast.makeText(getContext(),
						"请在 DemoApplication.java文件输入正确的授权Key！",
						Toast.LENGTH_LONG).show();
			}
		}
	}

	/**
	 * The default constructor
	 */
	public IMDroid() {
		instance = this;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see android.app.Application#onCreate()
	 */
	public void onCreate() {
		super.onCreate();
		// 启动通知服务
		// if (IMDroid.hasRegister()) {
		// Intent i = new Intent(Intent.ACTION_RUN);
		// i.setClass(this, NotificationService.class);
		// this.startService(i);
		// }

		// // 初始化地图管理对象，只能有一个
		// mBMapMan = new BMapManager(this);
		// mBMapMan.init(getResources().getString(R.string.baidu_map_key),
		// new MyGeneralListener());
		// // mBMapMan.getLocationManager().setNotifyInternal(ONE_MINUTE + 1,
		// // ONE_MINUTE);
		// // // 注册基站定位
		// // mBMapMan.getLocationManager().enableProvider(
		// // MKLocationManager.MK_NETWORK_PROVIDER);
		// mBMapMan.start();
		// 启动安全服务
		Intent i = new Intent(Intent.ACTION_RUN);
		i.setClass(this, SecurityService.class);
		this.startService(i);

		// 各种初始化
		SpeechRecog.init();
		Weibo.toAuth = true; // 微博开机登录
		// Weixin.init();
		Record.init();
		FloatView.init();
		Tts.init();

		// 设置默认值
		initialize();

		// 初始化地图
		initEngineManager(this);

		// 发起定位请求
		locationClient = new LocationClient(this);
		locationClient.registerLocationListener(myListener);
		// 设置定位参数
		LocationClientOption option = new LocationClientOption();
		option.setOpenGps(true);
		option.setAddrType("all");// 返回的定位结果包含地址信息
		option.setCoorType("bd09ll");// 返回的定位结果是百度经纬度,默认值gcj02
		option.setScanSpan(10000);// 设置发起定位请求的间隔时间为5000ms
		option.disableCache(false);
		locationClient.setLocOption(option);
		locationClient.start();
		if (locationClient != null && locationClient.isStarted())
			locationClient.requestLocation();

		ACRA.init(this);
		ErrorReporter reporter = ACRA.getErrorReporter();
		reporter.removeAllReportSenders();
		reporter.addReportSender(new CrashReportSender());
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see android.app.Application#onTerminate()
	 */
	public void onTerminate() {
		if (locationClient != null)
			locationClient.stop();

		// 浮动窗释放
		FloatView.finish();
		// 停止地图管理器
		if (mBMapMan != null) {
			mBMapMan.stop();
			mBMapMan.destroy();
			mBMapMan = null;
		}
		// 停止安全服务
		Intent i = new Intent(this, SecurityService.class);
		this.stopService(i);

		// 停止通知服务
		// stopService(new Intent(this, NotificationService.class));

		super.onTerminate();
	}

	public void initEngineManager(Context context) {
		if (mBMapMan == null) {
			mBMapMan = new BMapManager(context);
		}

		if (!mBMapMan.init(getResources().getString(R.string.baidu_map_key),
				new MyGeneralListener())) {
			Toast.makeText(getContext(), "BMapManager  初始化错误!",
					Toast.LENGTH_LONG).show();
		}
	}

	/**
	 * Check if the device has register
	 * 
	 * @return if the device has register
	 */
	public static boolean hasRegister() {
		return (IMDroid.getUser() != null && IMDroid.getUser().getUser_id() > 0);
	}

	/**
	 * Get the Context
	 * 
	 * @return The context
	 */
	public static Context getContext() {
		return instance;
	}

	private static Handler handler;

	public static void runInMainLooper(Runnable r) {
		if (handler == null)
			handler = new Handler(Looper.getMainLooper());
		handler.post(r);
	}

	public static void runInMainLooper(int delayMilliSecs, Runnable r) {
		if (handler == null)
			handler = new Handler(Looper.getMainLooper());
		handler.postDelayed(r, delayMilliSecs);
	}

	/**
	 * Get the imei number of devices
	 * 
	 * @return the imei number of devices
	 */
	public static String getDeviceIMEI() {
		TelephonyManager tm = (TelephonyManager) getContext().getSystemService(
				Context.TELEPHONY_SERVICE);
		// Log.d(TAG, "-----------" + tm.getDeviceId());
		// return "999990000000005";
		// return "666660000000006";
		// return "777772222222221";
		// return "555553333333335";
		// return "355600828041838"; // sliant's phone
		return tm.getDeviceId();
	}

	/**
	 * Get the imei number of devices
	 * 
	 * @return the imei number of devices
	 */
	public static String getDeviceSIM() {
		TelephonyManager tm = (TelephonyManager) getContext().getSystemService(
				Context.TELEPHONY_SERVICE);
		// return "15626013626"; // sliant's phone
		return tm.getLine1Number();
	}

	/**
	 * Load the users
	 */
	@SuppressLint("SimpleDateFormat")
	private static void loadUser() {
		SharedPreferences preference = PreferenceManager
				.getDefaultSharedPreferences(IMDroid.getContext());
		Resources resources = IMDroid.getContext().getResources();

		if (preference == null || preference.getInt("User_id", -1) <= 0) {
			currentUser = null;
			return;
		}
		currentUser = new User();

		// 用户ID
		currentUser.setUser_id(preference.getInt("User_id", -1));

		TelephonyManager tm = (TelephonyManager) getContext().getSystemService(
				Context.TELEPHONY_SERVICE);
		// 车机-IMEI
		// currentUser.setImei_number(tm.getLine1Number());
		currentUser.setImei_number(tm.getDeviceId());
		// 车机-SIM卡号码
		currentUser.setSim_number(preference.getString(
				resources.getString(R.string.KEY_SIM_NUMBER), null));
		// 用户名称
		currentUser.setUser_name(preference.getString(
				resources.getString(R.string.KEY_USER_NAME), null));
		// 用户手机号码
		currentUser.setMobile_phone(preference.getString(
				resources.getString(R.string.KEY_MOBILE_PHONE), null));
		// 车型
		currentUser.setVechile_model(preference.getString(
				resources.getString(R.string.KEY_VEHICLE_MODEL), null));
		// 车牌号码
		currentUser.setBoard_plate(preference.getString(
				resources.getString(R.string.KEY_BOARD_PLATE), null));
		// 车架号码
		currentUser.setFrame_number(preference.getString(
				resources.getString(R.string.KEY_FRAME_NUMBER), null));
		// 发动机号
		currentUser.setEngine_number(preference.getString(
				resources.getString(R.string.KEY_ENGINE_NUMBER), null));
		// 昵称
		currentUser.setNickname(preference.getString(
				resources.getString(R.string.KEY_NICKNAME), null));
		// 车队密码
		currentUser.setTeam_access_code(preference.getString(
				resources.getString(R.string.KEY_TEAM_ACCESS_CODE), null));

		// 购买日期
		if (preference.getString("Purchase_date", null) != null) {
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
			try {
				Date purchaseDate = sdf.parse(preference.getString(
						resources.getString(R.string.KEY_PURCHASE_DATE), null));
				currentUser.setPurchase_date(purchaseDate);
			} catch (ParseException e) {
				Log.d(TAG, e.getMessage());
			}
		}
		// 微博账号
		currentUser.setWeibo_account(preference.getString(
				resources.getString(R.string.KEY_WEIBO_ACCOUNT), null));
		// 性别
		currentUser.setGender(preference.getString(
				resources.getString(R.string.KEY_GENDER), null));
	}

	/**
	 * Register the user
	 */
	@SuppressLint("SimpleDateFormat")
	public static void registerUser(User user) {
		SharedPreferences preference = PreferenceManager
				.getDefaultSharedPreferences(IMDroid.getContext());
		Editor editor = preference.edit();
		Resources resources = IMDroid.getContext().getResources();

		editor.putInt("User_id", user.getUser_id());

		editor.putString(resources.getString(R.string.KEY_IMEI_NUMBER),
				user.getImei_number());
		editor.putString(resources.getString(R.string.KEY_SIM_NUMBER),
				user.getSim_number());
		editor.putString(resources.getString(R.string.KEY_USER_NAME),
				user.getUser_name());
		editor.putString(resources.getString(R.string.KEY_MOBILE_PHONE),
				user.getMobile_phone());
		editor.putString(resources.getString(R.string.KEY_VEHICLE_MODEL),
				user.getVechile_model());
		editor.putString(resources.getString(R.string.KEY_BOARD_PLATE),
				user.getBoard_plate());
		editor.putString(resources.getString(R.string.KEY_FRAME_NUMBER),
				user.getFrame_number());
		editor.putString(resources.getString(R.string.KEY_ENGINE_NUMBER),
				user.getEngine_number());
		editor.putString(resources.getString(R.string.KEY_NICKNAME),
				user.getNickname());
		editor.putString(resources.getString(R.string.KEY_TEAM_ACCESS_CODE),
				user.getTeam_access_code());

		if (user.getPurchase_date() != null) {
			SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
			editor.putString(resources.getString(R.string.KEY_PURCHASE_DATE),
					format.format(user.getPurchase_date()));
		}
		editor.putString(resources.getString(R.string.KEY_WEIBO_ACCOUNT),
				user.getWeibo_account());
		editor.putString(resources.getString(R.string.KEY_GENDER),
				user.getGender());
		editor.commit();
		currentUser = user;
	}

	/**
	 * Refresh the current user
	 * 
	 * @return the current user
	 */
	public static void refreshUser() {
		loadUser();
	}

	/**
	 * Get the current use
	 * 
	 * @return the current user
	 */
	public static User getUser() {
		if (currentUser == null)
			loadUser();
		return currentUser;
	}

	/**
	 * Register the user
	 * 
	 * @param context
	 *            the context
	 * @param user
	 *            the register user
	 */
	public static void register(Context context, User user) {
		// UserProcess process = (UserProcess) ProcessFactory
		// .getProcess(UserProcess.class);
		// try {
		// 跳转到首页
		Intent intent = new Intent();
		intent.setClass(context, HomeActivity.class);
		context.startActivity(intent);

		// process.postUser(user);

		// } catch (IOException e) {
		// e.printStackTrace();
		// }
	}

	/**
	 * Set the destination
	 * 
	 * @param destination
	 *            the destination
	 */
	public static void setDestination(Destination destination) {
		SharedPreferences preference = PreferenceManager
				.getDefaultSharedPreferences(IMDroid.getContext());
		Editor editor = preference.edit();
		editor.putString("Destination", "1");
		editor.putString("DestinationName", destination.getAddress());
		editor.putFloat("DestinationLongitude", destination.getLongitude());
		editor.putFloat("DestinationLatitude", destination.getLatitude());

		editor.commit();
	}

	/**
	 * Check if receive the destination
	 * 
	 * @return if receive the destination
	 */
	public static boolean hasDestination() {
		SharedPreferences preference = PreferenceManager
				.getDefaultSharedPreferences(IMDroid.getContext());
		String name = preference.getString("Destination", null);
		return (name != null && name.length() > 0);
	}

	/**
	 * Get the destination
	 * 
	 * @return the destination
	 */
	public static Destination getDestination() {
		SharedPreferences preference = PreferenceManager
				.getDefaultSharedPreferences(IMDroid.getContext());
		String name = preference.getString("Destination", null);
		if (name == null || name.trim().length() <= 0)
			return null;

		Destination destination = new Destination(preference.getString(
				"DestinationName", null), preference.getFloat(
				"DestinationLongitude", 0), preference.getFloat(
				"DestinationLatitude", 0));

		// remove in the reference
		Editor editor = preference.edit();
		editor.remove("Destination");
		editor.remove("DestinationName");
		editor.remove("DestinationLongitude");
		editor.remove("DestinationLatitude");
		editor.commit();
		return destination;
	}

	/**
	 * Get a unique message id.
	 * 
	 * @return
	 */
	public static int getNextMessageId() {
		SharedPreferences sp = PreferenceManager
				.getDefaultSharedPreferences(instance);
		int id = sp.getInt("message_id", 1) + 1;
		sp.edit().putInt("message_id", id).commit();
		return id;
	}

	/**
	 * 
	 */
	private void initialize() {
		SharedPreferences sp = PreferenceManager
				.getDefaultSharedPreferences(IMDroid.getContext());
		Editor ed = PreferenceManager.getDefaultSharedPreferences(
				IMDroid.getContext()).edit();
		Resources resources = this.getResources();
		// 每个文件的文件最大时间 (默认600秒)
		if (sp.getInt(KEY_REC_FILE_LEN, 0) <= 0)
			ed.putInt(KEY_REC_FILE_LEN, 600);

		// 目录下最多的文件个数(默认128个)
		if (sp.getInt(KEY_REC_FILE_COUNT, 0) <= 0)
			ed.putInt(KEY_REC_FILE_COUNT, 128);
		// 是否打开安防模块
		if (sp.getBoolean(resources.getString(R.string.KEY_SEC_OPEN), true))
			ed.putBoolean(resources.getString(R.string.KEY_SEC_OPEN), true);
		// 是否短信通知
		if (sp.getBoolean(resources.getString(R.string.KEY_SEC_SMS), true))
			ed.putBoolean(resources.getString(R.string.KEY_SEC_SMS), true);
		// 是否拍照
		if (sp.getBoolean(resources.getString(R.string.KEY_SEC_PIC), true))
			ed.putBoolean(resources.getString(R.string.KEY_SEC_PIC), true);
		// 震动灵敏度
		if (sp.getInt(resources.getString(R.string.KEY_SEC_ADD_CEN), 0) <= 0)
			ed.putInt(resources.getString(R.string.KEY_SEC_ADD_CEN), 15);
		// 报告GPS坐标的时间间隔
		if (sp.getInt(resources.getString(R.string.KEY_SEC_GPS_INT), 0) <= 0)
			ed.putInt(resources.getString(R.string.KEY_SEC_GPS_INT), 15);
		ed.commit();
	}

	/**
	 * Get the current location
	 * 
	 * @return the currentLocation
	 */
	public static BDLocation getCurrentLocation() {
		return currentLocation;
	}

	/**
	 * Set the current location
	 * 
	 * @param currentLocation
	 *            the currentLocation to set
	 */
	public static void setCurrentLocation(BDLocation currentLocation) {
		IMDroid.currentLocation = currentLocation;
	}

	/**
	 * Get the current location
	 * 
	 * @return the currentLocation
	 */
	public static GeoPoint getCurrentGeoPoint() {

		return (currentLocation != null) ? new GeoPoint(
				(int) (currentLocation.getLatitude() * 1e6),
				(int) (currentLocation.getLongitude() * 1e6)) : null;
	}

	/**
	 * Get if the battery is charing now
	 * 
	 * @return the batteryCharge
	 */
	public static boolean isBatteryCharge() {
		return batteryCharge;
	}

	/**
	 * Set if the battery is charing now
	 * 
	 * @param batteryCharge
	 *            the batteryCharge to set
	 */
	public static void setBatteryCharge(boolean batteryCharge) {
		IMDroid.batteryCharge = batteryCharge;
	}

	/**
	 * Get the version number of the application
	 * 
	 * @return the version number of the application
	 * @throws NameNotFoundException
	 */
	public static String getAppVersion() throws NameNotFoundException {
		// 版本名
		PackageManager manager = getContext().getPackageManager();
		PackageInfo info = manager.getPackageInfo(
				getContext().getPackageName(), 0);
		return info.versionName;
	}

	/**
	 * Get the last contact sync date
	 * 
	 * @return the date of last contact last sync
	 */
	public static Date getContactLastSync() {
		SharedPreferences prefs = PreferenceManager
				.getDefaultSharedPreferences(IMDroid.getContext());
		long time = prefs.getLong("contactLastSync", 0);
		return new Date(time);

	}

	/**
	 * Set the last contact sync date
	 * 
	 * @param date
	 *            the date of the contact last sync
	 */
	public static void setContactLastSync(Date date) {
		SharedPreferences prefs = PreferenceManager
				.getDefaultSharedPreferences(IMDroid.getContext());
		Editor editor = prefs.edit();
		editor.putLong("contactLastSync", date.getTime());
		editor.commit();
	}

	// /**
	// * Set the weibo login
	// *
	// * @param weiBoLogin
	// */
	// public static void setWeiboLogin(boolean weiBoLogin) {
	// SharedPreferences prefs = PreferenceManager
	// .getDefaultSharedPreferences(IMDroid.getContext());
	// Editor editor = prefs.edit();
	// editor.putBoolean("WeiBoLogin", weiBoLogin);
	// editor.commit();
	//
	// }

	// /**
	// * Get the weibo login
	// */
	// public static boolean getWeiboLogin() {
	// SharedPreferences prefs = PreferenceManager
	// .getDefaultSharedPreferences(IMDroid.getContext());
	// return prefs.getBoolean("WeiBoLogin", false);
	// }

	/**
	 * Set the weibo login
	 * 
	 * @param weiBoLogin
	 */
	public static void setWeiboLoginRemind(boolean weiBoLogin) {
		SharedPreferences prefs = PreferenceManager
				.getDefaultSharedPreferences(IMDroid.getContext());
		Editor editor = prefs.edit();
		editor.putBoolean("WeiBoLoginRemind", weiBoLogin);
		editor.commit();

	}

	/**
	 * Get the weibo login
	 */
	public static boolean getWeiboLoginRemind() {
		SharedPreferences prefs = PreferenceManager
				.getDefaultSharedPreferences(IMDroid.getContext());
		return prefs.getBoolean("WeiBoLoginRemind", true);
	}

	// 安防灵敏度
	public static float getAntiTheftTolerance() {
		return PreferenceManager.getDefaultSharedPreferences(
				IMDroid.getContext()).getInt(
				IMDroid.getContext().getResources()
						.getString(R.string.KEY_SEC_ADD_CEN), 15) / 10;

	}

	// 后台录像选项
	public static boolean getRecordBackground() {
		return PreferenceManager.getDefaultSharedPreferences(
				IMDroid.getContext()).getBoolean(
				IMDroid.getContext().getResources()
						.getString(R.string.KEY_REC_BACKGOUND), false);
	}

	// 后台录像选项
	public static void setRecordBackground(boolean value) {
		SharedPreferences prefs = PreferenceManager
				.getDefaultSharedPreferences(IMDroid.getContext());
		Editor editor = prefs.edit();
		editor.putBoolean(
				IMDroid.getContext().getResources()
						.getString(R.string.KEY_REC_BACKGOUND), value);
		editor.commit();
	}

	/**
	 * Get the location client
	 * 
	 * @return the locationClient
	 */
	public LocationClient getLocationClient() {
		return locationClient;
	}

	/**
	 * Set the location client
	 * 
	 * @param locationClient
	 *            the locationClient to set
	 */
	public void setLocationClient(LocationClient locationClient) {
		this.locationClient = locationClient;
	}

	/**
	 * The location listener
	 * 
	 */
	public static class MyLocationListener implements BDLocationListener {

		/*
		 * (non-Javadoc)
		 * 
		 * @see
		 * com.baidu.location.BDLocationListener#onReceiveLocation(com.baidu
		 * .location.BDLocation)
		 */
		public void onReceiveLocation(BDLocation arg0) {
			// Log.d(TAG,
			// "Lat:" + arg0.getLatitude() + " Lon" + arg0.getLongitude());
			currentLocation = arg0;
		}

		/*
		 * (non-Javadoc)
		 * 
		 * @see
		 * com.baidu.location.BDLocationListener#onReceivePoi(com.baidu.location
		 * .BDLocation)
		 */
		public void onReceivePoi(BDLocation arg0) {

		}
	}

	/**
	 * The error report sender
	 * 
	 */
	@SuppressLint("SimpleDateFormat")
	public class CrashReportSender implements ReportSender {
		/*
		 * (non-Javadoc)
		 * 
		 * @see
		 * org.acra.sender.ReportSender#send(org.acra.collector.CrashReportData)
		 */
		public void send(CrashReportData arg0) throws ReportSenderException {
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd_HH_mm_ss");
			String errorFileName = sdf.format(new Date()) + ".txt";
			File file = new File(TEMP_ERROR + errorFileName);
			BufferedWriter output = null;
			try {
				// 创建文件
				if (!file.exists())
					file.createNewFile();

				output = new BufferedWriter(new FileWriter(file));
				// 写入日志内容
				output.write("[ANDROID_VERSION]:"
						+ arg0.getProperty(ReportField.ANDROID_VERSION) + "\n");
				output.write("[APP_VERSION_CODE]:"
						+ arg0.getProperty(ReportField.APP_VERSION_CODE) + "\n");
				output.write("[APP_VERSION_NAME]:"
						+ arg0.getProperty(ReportField.APP_VERSION_NAME) + "\n");
				output.write("[APPLICATION_LOG]:"
						+ arg0.getProperty(ReportField.APPLICATION_LOG) + "\n");
				output.write("[AVAILABLE_MEM_SIZE]:"
						+ arg0.getProperty(ReportField.AVAILABLE_MEM_SIZE)
						+ "\n");
				output.write("[BRAND]:" + arg0.getProperty(ReportField.BRAND)
						+ "\n");
				output.write("[BUILD]:" + arg0.getProperty(ReportField.BUILD)
						+ "\n");
				output.write("[CRASH_CONFIGURATION]:"
						+ arg0.getProperty(ReportField.CRASH_CONFIGURATION)
						+ "\n");
				output.write("[CUSTOM_DATA]:"
						+ arg0.getProperty(ReportField.CUSTOM_DATA) + "\n");
				output.write("[DEVICE_FEATURES]:"
						+ arg0.getProperty(ReportField.DEVICE_FEATURES) + "\n");
				output.write("[DEVICE_ID]:"
						+ arg0.getProperty(ReportField.DEVICE_ID) + "\n");
				output.write("[DISPLAY]:"
						+ arg0.getProperty(ReportField.DISPLAY) + "\n");
				output.write("[DROPBOX]:"
						+ arg0.getProperty(ReportField.DROPBOX) + "\n");
				output.write("[DUMPSYS_MEMINFO]:"
						+ arg0.getProperty(ReportField.DUMPSYS_MEMINFO) + "\n");
				output.write("[ENVIRONMENT]:"
						+ arg0.getProperty(ReportField.ENVIRONMENT) + "\n");
				output.write("[EVENTSLOG]:"
						+ arg0.getProperty(ReportField.EVENTSLOG) + "\n");
				output.write("[FILE_PATH]:"
						+ arg0.getProperty(ReportField.FILE_PATH) + "\n");
				output.write("[INITIAL_CONFIGURATION]:"
						+ arg0.getProperty(ReportField.INITIAL_CONFIGURATION)
						+ "\n");
				output.write("[INSTALLATION_ID]:"
						+ arg0.getProperty(ReportField.INSTALLATION_ID) + "\n");
				output.write("[IS_SILENT]:"
						+ arg0.getProperty(ReportField.IS_SILENT) + "\n");
				output.write("[LOGCAT]:" + arg0.getProperty(ReportField.LOGCAT)
						+ "\n");
				output.write("[MEDIA_CODEC_LIST]:"
						+ arg0.getProperty(ReportField.MEDIA_CODEC_LIST) + "\n");
				output.write("[PACKAGE_NAME]:"
						+ arg0.getProperty(ReportField.PACKAGE_NAME) + "\n");
				output.write("[PHONE_MODEL]:"
						+ arg0.getProperty(ReportField.PHONE_MODEL) + "\n");
				output.write("[PRODUCT]:"
						+ arg0.getProperty(ReportField.PRODUCT) + "\n");
				output.write("[RADIOLOG]:"
						+ arg0.getProperty(ReportField.RADIOLOG) + "\n");
				output.write("[REPORT_ID]:"
						+ arg0.getProperty(ReportField.REPORT_ID) + "\n");
				output.write("[SETTINGS_SECURE]:"
						+ arg0.getProperty(ReportField.SETTINGS_SECURE) + "\n");
				output.write("[SETTINGS_SYSTEM]:"
						+ arg0.getProperty(ReportField.SETTINGS_SYSTEM) + "\n");
				output.write("[SHARED_PREFERENCES]:"
						+ arg0.getProperty(ReportField.SHARED_PREFERENCES)
						+ "\n");
				output.write("[STACK_TRACE]:"
						+ arg0.getProperty(ReportField.STACK_TRACE) + "\n");
				output.write("[THREAD_DETAILS]:"
						+ arg0.getProperty(ReportField.THREAD_DETAILS) + "\n");
				output.write("[TOTAL_MEM_SIZE]:"
						+ arg0.getProperty(ReportField.TOTAL_MEM_SIZE) + "\n");
				output.flush();
				output.close();
			} catch (IOException e) {
				e.printStackTrace();
			} finally {

				try {
					if (output != null)
						output.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			FTPClient ftpClient = new FTPClient();
			FileInputStream input = null;
			try {
				ftpClient.connect(HttpHelper.ftpAddress);
				ftpClient.login("error", "error");
				ftpClient.changeWorkingDirectory("/error");
				ftpClient.setBufferSize(1024);
				ftpClient.setControlEncoding("UTF-8");
				ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);
				input = new FileInputStream(file);
				ftpClient.storeFile(errorFileName, input);
			} catch (IOException e) {
				e.printStackTrace();
			} finally {
				try {
					if (input != null)
						input.close();

					if (ftpClient != null && ftpClient.isConnected())
						ftpClient.disconnect();

				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		}
	}

	/**
	 * @return the last sim subscriber id
	 */
	public static String getLastSIMSubscriberId() {
		SharedPreferences prefs = PreferenceManager
				.getDefaultSharedPreferences(IMDroid.getContext());
		return prefs.getString("lastSIMSubscriberId", "");
	}

	/**
	 * @return the last sim subscriber id
	 */
	public static void setLastSIMSubscriberId(String sIMSubscriberId) {
		SharedPreferences prefs = PreferenceManager
				.getDefaultSharedPreferences(IMDroid.getContext());
		Editor editor = prefs.edit();
		editor.putString("lastSIMSubscriberId", sIMSubscriberId);
		editor.commit();
	}
}
